//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Discussions.Components;
using System.Text;
using CommunityServer.Mail.Common.Components;

namespace CommunityServer.Discussions.Controls
{
	/// <summary>
	/// Summary description for ForumSubscriptionView.
	/// </summary>
	public class ForumSubscriptionView: TemplatedWebControl
	{
		CSContext csContext = CSContext.Current;
		Hashtable subscriptionTypesBySectionID = null;

		protected EmailSubscriptionType GetSubscriptionType(int sectionID)
		{
			if (subscriptionTypesBySectionID == null)
				subscriptionTypesBySectionID = ThreadTracking.GetSubscriptionTypesBySectionID(csContext.User.UserID);

			if (subscriptionTypesBySectionID.ContainsKey(sectionID))
				return (EmailSubscriptionType) subscriptionTypesBySectionID[sectionID];
			else
				return EmailSubscriptionType.None;
		}

		#region Child Controls

		protected Repeater groupRepeater;
		protected IButton saveButton;
		protected StatusMessage statusMessage;
		
		#endregion

		protected override void OnInit(EventArgs e) 
		{
			if (csContext.User.IsAnonymous)
				Page.Response.Redirect(SiteUrls.Instance().Login);

			if (SkinName == null)                
				ExternalSkinFileName = "View-ForumSubscriptionView.ascx";
			else 
				ExternalSkinFileName = SkinName;
			
			base.OnInit(e);
		}
		
		protected override void OnLoad(EventArgs e) 
		{
			base.OnLoad(e);
		}

		#region DataBind

		public override void DataBind() 
		{
			base.DataBind();

			ArrayList forumGroups = null;

			// Don't data bind if the data source is already populated
			//
			if (groupRepeater.DataSource != null)
				return;

			forumGroups = ForumGroups.GetForumGroups(true);

			Head.AddSiteNameTitle(ResourceManager.GetString("ForumSubscriptionView_Title"), Context);
			UsersOnline.SetLocation(ResourceManager.GetString("ForumSubscriptionView_Title"));
			
			// Databind if we have values
			//
			if (forumGroups.Count > 0) 
			{
				groupRepeater.DataSource = forumGroups;
				groupRepeater.DataBind();                
			}
		}

		#endregion		
		
		#region Skin
                
		protected override void AttachChildControls() 
		{
			groupRepeater = (Repeater) FindControl("ForumGroupRepeater");
			saveButton = FindButton("SaveButton");
			statusMessage = (StatusMessage) FindControl("StatusMessage");
			
			InitializeChildControls();
		}

		private void InitializeChildControls() 
		{
			if (groupRepeater != null)
				groupRepeater.ItemCreated += new RepeaterItemEventHandler(GroupRepeater_ItemCreated);		

			if (saveButton != null)
			{
				saveButton.Click += new System.EventHandler(SaveButton_Click);
				saveButton.Text = ResourceManager.GetString("Save");
			}

			DataBind();
		}
		        
		#endregion

		#region Event Handlers

		private void GroupRepeater_ItemCreated(Object sender, RepeaterItemEventArgs e) 
		{
			Group group = e.Item.DataItem as Group;
			if (group == null)
				return;

			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
			{
				Repeater forumRepeater = e.Item.FindControl("ForumRepeater") as Repeater;
				HyperLink groupName = e.Item.FindControl("ForumGroupName") as HyperLink;
                				
				if (groupName != null)
				{
					groupName.Text = group.Name;				
					groupName.NavigateUrl = SiteUrls.Instance().ForumGroup(group.GroupID);
				}
				
				if (forumRepeater != null)
				{
					ArrayList forums = new ArrayList();
					foreach (Forum f in Forums.GetForumsByForumGroupID(group.GroupID))
					{
						if (f.ForumType != ForumType.Link)
						{
							forums.Add(new ForumAndDepth(f, 0));
							AddSubForums(forums, f, 0);
						}
					}

					forumRepeater.ItemCreated += new RepeaterItemEventHandler(ForumRepeater_ItemCreated);
					forumRepeater.DataSource = forums;
					forumRepeater.DataBind();
				}
			}
		}

		private void ForumRepeater_ItemCreated(Object sender, RepeaterItemEventArgs e) 
		{
			ForumAndDepth forumAndDepth = e.Item.DataItem as ForumAndDepth;
			if (forumAndDepth == null)
				return;

			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
			{
				HyperLink forumName = e.Item.FindControl("ForumName") as HyperLink;
				IText forumDescription = CommunityServer.Controls.TextControlHelper.Create(e.Item.FindControl("ForumDescription"));
                IText indentation = CommunityServer.Controls.TextControlHelper.Create(e.Item.FindControl("Indentation"));
				HyperLink emailAddress = e.Item.FindControl("EmailAddress") as HyperLink;
				CheckBox isSubscribed = (CheckBox) e.Item.FindControl("IsSubscribed");
				HyperLink isMailingList = e.Item.FindControl("IsMailingList") as HyperLink;
				Control isNotMailingList = e.Item.FindControl("IsNotMailingList");

				if (forumName != null)
				{
					forumName.Text = forumAndDepth.Forum.Name;
					forumName.NavigateUrl = ForumUrls.Instance().Forum(forumAndDepth.Forum.SectionID);
				}

				if (emailAddress != null)
				{
					if (forumAndDepth.MailingList != null)
					{
						emailAddress.Text = forumAndDepth.MailingList.DetermineEmailAddress();
						emailAddress.NavigateUrl = "mailto:" + forumAndDepth.MailingList.DetermineEmailAddress();
					}
					else
						emailAddress.Visible = false;
				}

				if (isMailingList != null)
				{
					isMailingList.Visible = forumAndDepth.MailingList != null;
					isMailingList.NavigateUrl = ForumUrls.Instance().EmailInformation(forumAndDepth.Forum.SectionID);
				}

				if (isNotMailingList != null)
					isNotMailingList.Visible = forumAndDepth.MailingList == null;

				if (forumDescription != null)
					forumDescription.Text = forumAndDepth.Forum.Description;

				if (indentation != null)
				{
					StringBuilder identationText = new StringBuilder();
					string text = indentation.Text;
					for (int i = 0; i < forumAndDepth.Depth; i++)
					{
						identationText.Append(text);
					}

					indentation.Text = identationText.ToString();
				}

				if (isSubscribed != null)
				{
					if (!Page.IsPostBack)
					{
						if (Permissions.ValidatePermissions(forumAndDepth.Forum, Permission.Read, CSContext.Current.User))
							isSubscribed.Checked = (GetSubscriptionType(forumAndDepth.Forum.SectionID) & EmailSubscriptionType.Post) > 0;
						else
						{
							isSubscribed.Checked = false;
							isSubscribed.Enabled = false;

							if((GetSubscriptionType(forumAndDepth.Forum.SectionID) & EmailSubscriptionType.Post) > 0)
								RemoveSubscriptionType(forumAndDepth.Forum, EmailSubscriptionType.Post);
						}
					}
				}
			}
		}

		private void SaveButton_Click(Object sender, EventArgs e)
		{
			if (groupRepeater != null)
			{
				foreach (RepeaterItem item in groupRepeater.Items)
				{
					Repeater forumRepeater = item.FindControl("ForumRepeater") as Repeater;
					if (forumRepeater != null)
					{
						foreach (RepeaterItem item2 in forumRepeater.Items)
						{
							CheckBox isSubscribed = item2.FindControl("IsSubscribed") as CheckBox;
							if (isSubscribed != null)
							{
								Forum forum = ((ForumAndDepth) ((ArrayList) forumRepeater.DataSource)[item2.ItemIndex]).Forum;
								
								if (isSubscribed.Checked)
									AddSubscriptionType(forum, EmailSubscriptionType.Post);
								else
									RemoveSubscriptionType(forum, EmailSubscriptionType.Post);
							}
						}
					}
				}
			}

			if (statusMessage != null)
			{
				statusMessage.Visible = true;
				statusMessage.Success = true;
				statusMessage.Text = ResourceManager.GetString("ForumSubscriptionView_SaveSuccessful");
			}
		}

		#region Helper Methods

		public void AddSubscriptionType(Forum forum, EmailSubscriptionType subType)
		{
			if (!Permissions.ValidatePermissions(forum, Permission.Read, CSContext.Current.User))
				return;
			
			EmailSubscriptionType current = GetSubscriptionType(forum.SectionID);
			if ((current & subType) == 0)
				ThreadTracking.SetSectionSubscriptionType(forum.SectionID, csContext.User.UserID, current | subType);
		}

		public void RemoveSubscriptionType (Forum forum, EmailSubscriptionType subType)
		{
			EmailSubscriptionType current = GetSubscriptionType(forum.SectionID);
			if ((current & subType) > 0)
				ThreadTracking.SetSectionSubscriptionType(forum.SectionID, csContext.User.UserID, EmailSubscriptionType.None);
		}

		public void AddSubForums(ArrayList forums, Forum parent, int depth)
		{
			depth++;
			if (parent.Sections == null)
				return;

			parent.Sections.Sort(new SectionSorter(SectionSortBy.Name));

			foreach (Forum f in parent.Sections)
			{
				if (f.ForumType != ForumType.Link)
				{
					forums.Add(new ForumAndDepth(f, depth));
					AddSubForums(forums, f, depth);
				}
			}
		}

		#endregion

		#endregion

		public class ForumAndDepth
		{
			public Forum Forum;
			public int Depth;
			public MailingList MailingList;

			public static bool checkMailingLists = CSContext.Current.SiteSettings.EnableMailGateway;

			public ForumAndDepth(Forum f, int depth)
			{
				this.Forum = f;
				this.Depth = depth;
				this.MailingList = null;

				if (checkMailingLists)
				{
					MailingList ml = MailingLists.GetMailingList(f.SectionID);
					if (ml != null && ml.IsMailingList && ml.IsActive)
						this.MailingList = ml;
				}
			}
		}
	}
}
